<template>
    <div>
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="800px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-tabs v-model="activeTab">
                <el-tab-pane label="黑名单列表" name="list">
                    <el-form :model="queryParams" inline class="mb-4">
                        <el-form-item label="微信号">
                            <el-input 
                                v-model="queryParams.wechat_code" 
                                placeholder="请输入微信号" 
                                clearable 
                                @keyup.enter="getBlacklist"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getBlacklist">查询</el-button>
                            <el-button @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                    
                    <el-table v-loading="loading" :data="blacklist" style="width: 100%">
                        <el-table-column prop="wechat_code" label="微信号" />
                        <el-table-column prop="create_time" label="添加时间" />
                        <el-table-column label="操作" width="120">
                            <template #default="scope">
                                <el-button 
                                    type="danger" 
                                    link 
                                    @click="handleDeleteBlacklist(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    
                    <div class="flex justify-end mt-4">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 50, 100]"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </el-tab-pane>
                
                <el-tab-pane label="添加黑名单" name="add">
                    <el-form :model="addForm" label-width="100px" :rules="rules" ref="addFormRef">
                        <el-alert
                            type="warning"
                            show-icon
                            :closable="false"
                            title="提示"
                            description="添加到黑名单的用户将不再自动投放"
                            class="mb-8"
                            style="margin-bottom: 20px;"
                        />
                        <el-form-item label="微信号" prop="wechat_code" style="margin-right: 10px;">
                            <el-input 
                                v-model="addForm.wechat_code" 
                                placeholder="请输入微信号" 
                                clearable 
                            />
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import { ElMessage } from 'element-plus'
// 删除axios导入
// import axios from 'axios'
import useUserStore from '@/stores/modules/user'
// 导入API函数
import { 
    apiTencentAdvertisingBlackListLists,
    apiTencentAdvertisingBlackListAdd,
    apiTencentAdvertisingBlackListDelete 
} from '@/api/tencent_advertising_user_ad_list'

const props = defineProps({
    ad_group_id: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['success', 'close'])
const popupRef = ref()
const popupTitle = ref('投放黑名单')
const activeTab = ref('list')
const loading = ref(false)
const blacklist = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userStore = useUserStore()

// 查询参数
const queryParams = reactive({
    ad_group_id: '',
    wechat_code: '',
    page: 1,
    limit: 10
})

// 添加表单
const addFormRef = ref()
const addForm = reactive({
    ad_group_id: '',
    wechat_code: ''
})

// 表单验证规则
const rules = {
    wechat_code: [
        { required: true, message: '请输入微信号', trigger: 'blur' }
    ]
}

// 打开弹窗
const open = (type: string) => {
    popupRef.value.open()
    activeTab.value = 'list'
    queryParams.ad_group_id = props.ad_group_id
    addForm.ad_group_id = props.ad_group_id
    getBlacklist()
}

// 获取黑名单列表
const getBlacklist = async () => {
    loading.value = true
    try {
        const params = {
            ad_group_id: queryParams.ad_group_id,
            wechat_code: queryParams.wechat_code,
            page: currentPage.value,
            limit: pageSize.value
        }
        
        const res = await apiTencentAdvertisingBlackListLists(params)
        console.log('getBlacklist', res)
        // 根据实际返回的数据结构调整这里
        blacklist.value = res.lists || []
        total.value = res.count || 0
    } catch (error) {
        console.error('获取黑名单列表出错:', error)
        ElMessage.error('获取黑名单列表失败')
    } finally {
        loading.value = false
    }
}

// 删除黑名单
const handleDeleteBlacklist = async (id: number) => {
    try {
        await feedback.confirm('确定要从黑名单中删除该微信号吗？')
        
       await apiTencentAdvertisingBlackListDelete({ id })
      
        getBlacklist()
    } catch (error) {
        console.error('删除黑名单出错:', error)
    }
}

// 提交表单
const handleSubmit = async () => {
    if (activeTab.value === 'add') {
        addFormRef.value.validate(async (valid: boolean) => {
            if (valid) {
                try {
                    const params = {
                        ad_group_id: addForm.ad_group_id,
                        wechat_code: addForm.wechat_code
                    }
                    
                    await apiTencentAdvertisingBlackListAdd(params)
               
                    addForm.wechat_code = ''
                    activeTab.value = 'list'
                    getBlacklist()
                    emit('success')
                } catch (error) {
                    console.error('添加黑名单出错:', error)
                }
            }
        })
    } else {
        popupRef.value.close()
    }
}

// 重置查询
const resetQuery = () => {
    queryParams.wechat_code = ''
    currentPage.value = 1
    getBlacklist()
}

// 分页大小变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getBlacklist()
}

// 页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getBlacklist()
}

// 关闭弹窗
const handleClose = () => {
    addForm.wechat_code = ''
    emit('close')
}

defineExpose({
    open
})
</script>